const { query } = require('../../../lib/db');
const { authenticateToken } = require('../../../lib/auth');

async function handler(req, res) {
  if (req.method !== 'GET') {
    return res.status(405).json({
      success: false,
      message: '方法不允许'
    });
  }

  try {
    // 获取统计数据
    const summaryStats = await query(`
      SELECT 
        COUNT(*) as total_tickets,
        COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_tickets,
        COUNT(CASE WHEN status = 'in_progress' THEN 1 END) as in_progress_tickets,
        COUNT(CASE WHEN status = 'resolved' THEN 1 END) as resolved_tickets
      FROM tickets
    `);
    
    const todoStats = await query(`
      SELECT 
        COUNT(*) as total_todos,
        COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_todos,
        COUNT(CASE WHEN status = 'completed' THEN 1 END) as completed_todos
      FROM todos
    `);
    
    const summary = {
      total_tickets: summaryStats[0].total_tickets,
      pending_tickets: summaryStats[0].pending_tickets,
      in_progress_tickets: summaryStats[0].in_progress_tickets,
      resolved_tickets: summaryStats[0].resolved_tickets,
      pending_todos: todoStats[0].pending_todos,
      completed_todos: todoStats[0].completed_todos
    };
    
    // 获取最近工单
    const recent_tickets = await query(`
      SELECT t.*, u.name as creator_name, s.name as support_staff_name
      FROM tickets t
      LEFT JOIN users u ON t.user_id = u.id
      LEFT JOIN users s ON t.support_staff_id = s.id
      ORDER BY t.created_at DESC
      LIMIT 5
    `);

    res.status(200).json({
      success: true,
      data: {
        summary,
        recent_tickets
      }
    });

  } catch (error) {
    console.error('仪表盘统计错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

export default authenticateToken(handler);